<template>
	<scroll-view class="post-content" scroll-y="true" :scroll-into-view="scrollIntoViewId">
		<view class="post">
			<view class="item">
				<view class="level" >
					<view class="level-left" @click="toHomePage(postDetail)">
						<u-avatar class="avatar" mode="aspectFill" :src="authorInfo.user_avatar" size="35"></u-avatar>
						<view class="level-left-name">
							<view class="name">{{authorInfo.user_name}}</view>
							<view class="date">{{postDetail.createTime}}</view>
						</view>
					</view>
						<view class="level-right" v-if="postDetail.isFollowed==0&&postDetail.userId!=$store.state.userInfo.userId" @click="onFollow()">
							<u-icon name="plus" class="icon" :plain="true" size="14" shape="circle" color="#FE4E4E"></u-icon>关注
						</view>
						<!-- <view class="level-right active" v-show="postDetail.isFollowed==1&&postDetail.userId!=$store.state.userInfo.userId" @click="onFollow()" >
							<u-icon name="checkmark" class="icon" :plain="true" size="14" shape="circle" color="#ccc"></u-icon>已关注
						</view> -->
				</view>
				
				<post-shrink
					:text="postDetail.content" 
					:line="30"
				/>
				
				<view class="level album">
					<view v-if="postDetail.files&&postDetail.files.length!=0&&postDetail.files.length === 4 && postDetail.files[0].isImage === 1" class="grid-tianzi">
						<view 
							v-for="(file, fileIndex) in postDetail.files" 
							:key="fileIndex" 
							class="grid-tianzi-item"
							@click.stop="previewImage(postDetail.files, fileIndex)"
						>
							<u-image 
								:src="file.fileUrl" 
								width="189" 
								height="189"
								mode="aspectFill"
							></u-image>
						</view>
					</view>
					<u-album
						v-else-if="postDetail.files&&postDetail.files.length!=0&&postDetail.files.length!=4 && postDetail.files[0].isImage==1" 
						:urls="postDetail.files"
						:keyName="'fileUrl'"
						:multipleSize="'222rpx'" 
						:singleSize="300"
					></u-album>
					<!--  #ifdef APP-PLUS || H5 -->
					<DomVideoPlayer
						v-if="postDetail.files&&postDetail.files.length!=0&&postDetail.files[0].isImage==0"
						@top.stop="fullScreen(index)"
						:src="postDetail.files[0].fileUrl"
						loop
						autoplay
					/>
					<!-- #endif -->
				</view>
				<view class="tags-section">
					<text class="tag-item" v-for="(i,j) in postTopics" :key="j">#{{i.title}}</text>
				</view>
				<view class="post-actions">
					<view class="post-actions-item" @click="shareWx()">
						<u-icon name="share" size="24" color="#000"></u-icon>
						<text class="post-actions-item-text">转发</text>
					</view>
					<!-- <view class="post-actions-item" @click="dropLike()">
						<u-icon :name="postDetail.like?'heart-fill':'heart'" :color="postDetail.like?'#ff5a5f':'#666'" size="24"></u-icon>
						<text class="post-actions-item-text">点赞</text>
					</view> -->
					<view class="post-actions-item" @click="openComment()">
						<u-icon name="chat" size="24" color="#000"></u-icon>
						<text class="post-actions-item-text">评论</text>
					</view>
					<view class="post-actions-item" @click="dropCollect()">
						<u-icon :name="postDetail.isCollected==1?'star-fill':'star'" :color="postDetail.isCollected==1?'#ff5a5f':'#000'" size="24"></u-icon>
						<text class="post-actions-item-text">收藏</text>
					</view>
					
				</view>
				<view class="" id="comment">
					<CComment 
						@touchstart="$refs.ccRef.closeComment()"  
						ref="ccRef" 
						:userInfo="authorInfo" 
						:tableData="tableData" 
						:tableTotal="tableTotal" 
						@likeFun="likeFun" 
						:deleteMode="deleteMode"
						@avatarFun="avatarFun"
						@replyFun="replyFun"
						@deleteFun="deleteFun"
					></CComment>
				</view>
				
			</view>
		</view>
	</scroll-view>
</template>

<script>
	import CComment from "@/components/XJ-comment/index";
	import PostShrink from "@/components/post-shrink/post-shrink"
	import { 
		getPostDetails,
		getClientFollow,
		getCommentList,
		getCommentChildrenList,
		addComment,
		removeComment,
		addCommentLike,
		cancelCommentLike,
		postClientCollect,
		postCancelCollect
	} from '@/request/api.js'
	// #ifdef APP-PLUS || H5
	import DomVideoPlayer from '@/components/DomVideoPlayer/DomVideoPlayer.vue'
	// #endif
	export default {
		components: {
			// #ifdef APP-PLUS || H5
			 DomVideoPlayer,
			// #endif
			CComment,
			PostShrink
		},
		data() {
			return {
				postId:null,
				postCreatorId:null,
				isScroll:false,
				postDetail:{},
				ccRef: null,
				userInfo: {},
				authorInfo:{},
				tableTotal: 0,
				tableData: [],
				deleteMode: "all",
				scrollIntoViewId: '',
				postTopics:[]//话题标签
			}
		},
		watch:{
			postDetail:{
				handler(newVal) {
				},
			}
		},
		onLoad(options) {
			this.initData()
		},
		onUnload() {
			// 页面卸载（返回）时，触发事件通知首页更新
			uni.$emit('updatePostData', {
				postId: this.postDetail.id,
				newState: {
					isLiked: this.postDetail.isLiked,
					likeCount: this.postDetail.likeCount,
					// 可以包含其他需要同步的字段
				}
			});
		},
		methods: {
			avatarFun(id){
				uni.navigateTo({
					url: '/pages_sub/user/others/others?userId='+id,
				});
			},
			initData() {
			    const eventChannel = this.getOpenerEventChannel();
			    
			    // 回调函数的参数 res 就是父页面 emit 的那个对象 { data: "..." }
			    eventChannel.on('sendInitData', (res) => { 
			        // 关键：需要从 res 中解构出 data 属性
			        if (res && res.data) {
			            try {
			                let data = JSON.parse(res.data);
			                console.log('成功解析到父页面数据:', data, data.item.userId==this.$store.state.userInfo.userId);
			                
			                // 确保 data.item 存在
			                if (data && data.item) {
			                    this.postId = data.item.id;
			                    this.postCreatorId = data.item.userId;
			                    this.authorInfo = {
			                        id: data.item.userId,
			                        user_name: data.item.userId == this.$store.state.userInfo.userId?this.$store.state.userInfo.nickName:data.item.nickName,
			                        user_avatar: data.item.userId == this.$store.state.userInfo.userId?this.$store.state.userInfo.avatar:data.item.avatar,
			                    };
			                    this.isScroll = data.scroll;
			                    this.postDetail = data.item;
			                    
			                    this.getPostDetail();
			                    this.getCommentLists();
			                } else {
			                    console.error('解析成功，但数据中缺少 item 属性。', data);
			                }
			
			            } catch (e) {
			                console.error('JSON.parse 解析父页面数据失败:', e);
			            }
			        } else {
			            console.error('从 eventChannel 接收到的数据格式不正确或为空。', res);
			        }
			    });
			},
			previewImage(files, currentIndex) {
				const urls = files.map(file => file.fileUrl);
				uni.previewImage({
					urls: urls,
					current: currentIndex,
					fail: (err) => {
						console.error('previewImage fail:', err);
					}
				});
			},
			// 获取评论列表
			getCommentLists(){
				getCommentList(this.postId).then((res)=>{
					this.tableTotal = Number(res.data.total) || 0; 
					this.tableData = res.data.rows&&res.data.rows.map(data=>{
						this.getCommentChildrenList(data.commentId)
						return{
							id: data.commentId,
							parent_id: null,
							reply_id: null,
							reply_name: null,
							user_name: data.nickName,
							user_avatar: data.avatar,
							user_content: data.content,
							is_like: data.isLiked,
							like_count: data.likeCount,
							create_time:data.createTime,
							user_id:data.userId,
						}
					})
				})
			},
			getCommentChildrenList(commentId){
				getCommentChildrenList(commentId).then((res)=>{
					let replyList = res.data.rows&& res.data.rows.map(data=>{
						return{
							id: data.commentId,
							parent_id: data.parentId,
							reply_id: data.replyToUserId,
							reply_name: data.replyToName,
							user_name: data.nickName,
							user_avatar: data.avatar,
							user_content: data.content,
							is_like: data.isLiked,
							like_count: data.likeCount,
							create_time:data.createTime,
							user_id:data.userId,
						}
					})
					
					this.tableData.push(...replyList)
				})
			},
			// 获取帖子详情
			getPostDetail(){
				getPostDetails(this.postId).then((res)=>{
					this.postTopics = res.data.data.postTopics
					if(this.isScroll=='true'){
						this.scrollToPosition()
					}
				})
			},
			scrollToPosition() {
				this.$nextTick(() => {
				    this.scrollIntoViewId = 'comment';
				});
			},
			// 关注
			onFollow(item,index){
				this.postDetail.isFollowed = this.postDetail.isFollowed == 0 ? this.postDetail.isFollowed = 1 : this.postDetail.isFollowed=0;
				getClientFollow({userId:this.postDetail.userId}).then(res=>{
					this.sendParent(4)
				})
			},
			onUnFollow(item,index){
				this.postDetail.isGZ = false
				uni.showToast({
					title: '取消关注成功！'
				});
			},
			// 聊天
			onChat(item){
				uni.navigateTo({
					url: '/pages_sub/user/chat/chat?user='+JSON.stringify(this.postDetail)
				});
			},
			// 打开回复评论
			openComment(){
				this.$refs.ccRef.newCommentFun();
			},
			// 点赞评论
			likeFun(params, callback) {
				console.log("likeFun", params,callback);
				if(params.params.is_like){
					addCommentLike(params.params.id).then(res=>{
						if(res.data.code!=200){
							callback(params)
						}
					})
				}else{
					cancelCommentLike(params.params.id).then(res=>{
						if(res.data.code!=200){
							callback(params)
						}
					})
				}
				// Implement your logic for likeFun
				
			},
			// 回复评论
			replyFun(params, callback) {
				// console.log("replyFun", params);
				let data = {
					postId:new Number(this.postId),
					userId:new Number(this.$store.state.userInfo.userId),
					parentId:new Number(params.params.parent_id )|| null,
					replyToUserId: new Number(params.params.reply_id ) || null,
					content: params.params.user_content || null,
					postCreatorId: new Number(this.postCreatorId )
				}
				console.log("replyFun", data);
				addComment( data ).then((res) => {
				    if (res.data.code==500) {
						uni.$u.toast(res.data.msg);
				    }else{
						// const data = { id: Math.random(res.data.data.commentId ) };
						const data = { id: res.data.data.commentId }; // 很重要的回参! 必须拿到后端返回评论id! 删除需要!
						console.log("data",data);
						this.sendParent(1)
						callback(data); // 目前为了展示效果, 直接执行callback
					}
				});
			},
			sendParent(type){
				// 触发父页面监听的 "returnData" 事件，回传数据
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.emit('returnData', { id: this.postId,userId:this.authorInfo.id, type: type,isLiked:this.postDetail.isLiked,likeCount:this.postDetail.likeCount,isCollected:this.postDetail.isCollected,collectCount:this.postDetail.collectCount,isFollowed:this.postDetail.isFollowed });
			},
			// 删除评论
			deleteFun({ params, mode }, callback) {
			
				console.log("deleteFun", { params, mode });
				// 当请求成功, 调用callback执行评论删除;
				switch (this.deleteMode) {
					case "bind":
				  // 逻辑: 调用接口进行评论内容修改 update
						setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
					break;
					case "only":
						// 逻辑: 调用接口删除一个评论 delete
						setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
					break;
					default:
						// all
						// 逻辑: 调用接口删除多个评论 [delete]
						// Demo如下:
						// let datas = {
						// 	commentId:
						// 	postId:
						// 	parentId:
						// 	replyCount:
						// }
						// removeComment()
						// axios.post("http://xxx/delete", { ids: params }).then((res) => {
						//   if (res.code === 0) {
						//     callback(res);
						//   }
						// });
						setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
					break;
				}
			},
			// 转发
			shareWx(){
				uni.share({
					provider: "weixin",
					scene: "WXSceneSession",
					type: 0,
					href: "http://uniapp.dcloud.io/",
					title: this.postDetail.name,
					summary: this.postDetail.describe,
					imageUrl: this.postDetail.avatar,
					success: function (res) {
						console.log("success:" + JSON.stringify(res));
					},
					fail: function (err) {
						console.log("fail:" + JSON.stringify(err));
					}
				});
			},
			// 点赞
			dropLike() {
			    const originalIsLiked = this.postDetail.isLiked;
			    const originalLikeCount = this.postDetail.likeCount;
			
			    // UI先行
			    this.postDetail.isLiked = originalIsLiked ? 0 : 1;
			    this.postDetail.likeCount = originalIsLiked ? originalLikeCount - 1 : originalLikeCount + 1;
			
			    // 决定API调用
			    const apiCall = originalIsLiked ? postCancelLike : postClientLike;
			    const params = { postId: this.postDetail.id, userId: this.$store.state.userInfo.userId };
			    
			    // 发起请求，处理失败
			    apiCall(params).then(res => {
					if (res.data && (res.data.code === 200 || res.data.code === 0)) {
						this.sendParent(0); // 可以在成功后发送通知
					} else {
						throw new Error(res.data.msg || '操作失败');
					}
				})
				.catch(err => {
					// 失败时回滚
					this.postDetail.isLiked = originalIsLiked;
					this.postDetail.likeCount = originalLikeCount;
					uni.showToast({ title: '操作失败，请稍后重试', icon: 'none' });
				});
			},
			// 收藏
			dropCollect() {
			    // 1. 保存原始状态，用于请求失败时回滚
			    const originalIsCollected = this.postDetail.isCollected;
			    const originalCollectCount = this.postDetail.collectCount;
			
			    // 2. UI先行：立即更新界面上的收藏状态和数量
			    this.postDetail.isCollected = originalIsCollected ? 0 : 1;
			    this.postDetail.collectCount = originalIsCollected ? originalCollectCount - 1 : originalCollectCount + 1;
			
			    // 3. 根据当前状态，决定调用“收藏”还是“取消收藏”的API
			    const apiCall = originalIsCollected ? postCancelCollect : postClientCollect;
			    
			    // 4. 发起网络请求，注意这里只处理失败情况
			    apiCall(this.postDetail.id).then(res => {
					// 请求成功
					if (res.data && (res.data.code === 200 || res.data.code === 0)) {
						// UI已经更新，这里只需处理成功后的逻辑，比如通知父组件
						this.sendParent(2); 
					} else {
						// 如果后端返回了业务错误码，也视为失败，进行回滚
						throw new Error(res.data.msg || '操作失败');
					}
				})
				.catch(err => {
					// 5. 请求失败时，将UI回滚到原始状态
					console.error('收藏/取消收藏失败:', err);
					this.postDetail.isCollected = originalIsCollected;
					this.postDetail.collectCount = originalCollectCount;
					uni.showToast({ title: '操作失败，请稍后重试', icon: 'none' });
				});
			},
		}
	}
</script>

<style lang="scss">
	.post-content{
		height: calc(100vh - 180rpx);
	}
	.album{
		// max-width: 600rpx;
		// max-height: 600rpx;
		display: inline-block;
		margin-top: 15rpx;
		position: relative;
		z-index: 1;
		.grid-tianzi {
			display: grid;
			flex: 1;
			grid-template-columns: repeat(2, 1fr);
			grid-auto-rows: 1fr;
			gap: 4px;
			
			.grid-tianzi-item {
				aspect-ratio: 1 / 1;
				overflow: hidden;
				// border-radius: 8rpx;
			}
		}
	}
.post{
	background-color: #FFFFFF;
	.item{
		background-color: #FFFFFF;
		padding: 10rpx 30rpx 0 30rpx;
	}
	.avatar{
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		border: 1rpx solid #FFAE1A;
	}
	.level-left-name{
		margin-left: 20rpx;
	}
	.level{
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin: 15rpx 0;
		.level-left{
			display: flex;
			align-items: center;
			
		}
		.level-right{
			display: flex;
			color: #FE4E4E;
			border: 1rpx solid #FE4E4E;
			border-radius: 50rpx;
			font-size: 26rpx;
			padding: 5rpx 15rpx;
			.icon{
				margin-right: 5rpx;
			}
		}
		.active{
			color: #cccccc;
			border: 1rpx solid #cccccc;
		}
	}
	.name{
		// font-weight: 700;
		font-size: 32rpx;
	}
	.date{
		color: #787878;
		font-size: 22rpx;
		margin-top: 5rpx;
	}
	.describe{
		/* text-indent: 2em; */
		// font-size:30rpx;
		
	}
	.label{
		font-size: 24rpx;
		color: #FFAE1A;
	}
	.image:nth-child(2){
		margin: 0 15rpx;
	}
	.image{
		justify-content: space-between;
	}
}
.tags-section {
	margin: 20rpx 0;
	.tag-item {
		color: #FFB327;
		margin-right: 15rpx;
		font-size: 26rpx;
	}
}
.post-actions{
	display: flex;
	color: #000;
	justify-content: space-between;
	font-size: 24rpx;
	position: fixed;
	bottom: 0rpx;
	padding-bottom: 20rpx;
	left: 50rpx;
	right: 50rpx;
	.post-actions-item{
		display: flex;
		align-items: center;
		&-text{
			min-width: 40rpx;
			text-align: center;
		}
	}
	.image{
		width: 48rpx;
		height: 48rpx;
		margin-right: 10rpx;
	}
	text{
		/* margin-bottom: 10rpx; */
	}
}
</style>
